const request = require('request');

const appID = 'your_app_id';
const appSecret = 'your_app_secret';

// 获取 Access Token
function getAccessToken(callback) {
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appSecret}`;
    request.get(url, (error, response, body) => {
        if (!error && response.statusCode === 200) {
            const data = JSON.parse(body);
            callback(data.access_token);
        }
    });
}

// 发送文本消息
function sendTextMessage(userOpenID, messageContent, accessToken) {
    const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${accessToken}`;
    const payload = {
        touser: userOpenID,
        msgtype: 'text',
        text: {
            content: messageContent
        }
    };
    
    const options = {
        uri: url,
        method: 'POST',
        json: payload
    };

    request(options, (error, response, body) => {
        if (!error && response.statusCode === 200) {
            console.log('Message sent successfully');
        } else {
            console.error('Error sending message:', body);
        }
    });
}

const userOpenID = 'user_openid_here';  // 用户的 OpenID
const messageContent = 'Hello, this is an automated message';

getAccessToken((accessToken) => {
    sendTextMessage(userOpenID, messageContent, accessToken);
});
